//package com.xqq.service;
//
//import com.alibaba.fastjson.JSON;
//import com.xqq.entity.TbLParamMalfunctionRecordDO;
//import com.xqq.respository.TbLParamMalfunctionRecordRepository;
//import org.elasticsearch.index.query.BoolQueryBuilder;
//import org.elasticsearch.index.query.QueryBuilder;
//import org.elasticsearch.index.query.QueryBuilders;
//import org.elasticsearch.search.SearchHit;
//import org.elasticsearch.search.aggregations.Aggregation;
//import org.elasticsearch.search.aggregations.AggregationBuilders;
//import org.elasticsearch.search.aggregations.Aggregations;
//import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
//import org.elasticsearch.search.aggregations.bucket.terms.Terms;
//import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
//import org.elasticsearch.search.aggregations.metrics.ParsedTopHits;
//import org.elasticsearch.search.aggregations.metrics.TopHits;
//import org.elasticsearch.search.sort.SortBuilders;
//import org.elasticsearch.search.sort.SortOrder;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.elasticsearch.core.AggregationsContainer;
//import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
//import org.springframework.data.elasticsearch.core.SearchHits;
//import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
//import org.springframework.data.elasticsearch.core.query.Query;
//import org.springframework.stereotype.Service;
//
//
//import java.util.ArrayList;
//import java.util.Arrays;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//import java.util.Optional;
//import java.util.Set;
//
//import static com.xqq.utils.Constants.ABNORMOL;
//import static com.xqq.utils.Constants.IS_BLACK;
//import static com.xqq.utils.Constants.IS_WHITE;
//import static com.xqq.utils.Constants.NOT_CLEANED;
//import static com.xqq.utils.Constants.NOT_DELETED;
//
//@Service
//public class TbLParamMalfunctionRecordService {
//
//    @Autowired
//    private TbLParamMalfunctionRecordRepository tbLParamMalfunctionRecordRepository;
//
//    @Autowired
//    private ElasticsearchRestTemplate elasticsearchRestTemplate;
//
//    public void saveRecord(TbLParamMalfunctionRecordDO record) {
//        tbLParamMalfunctionRecordRepository.save(record);
//    }
//
//    // 根据 ID 查找轨迹记录
//    public Optional<TbLParamMalfunctionRecordDO> findById(int id) {
//        return tbLParamMalfunctionRecordRepository.findById(id);
//    }
//
//    public List<TbLParamMalfunctionRecordDO> searchRecords(String startTime, String endTime, Set<String> newparamIdSet, Set<String> newmodelIdSet, Map<String, Integer> paramModelCountMap, int pageNum, int pageSize) {
//        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
//
//        // 1. 添加字段选择
//        queryBuilder.withFields("param_id", "model_id", "end_time", "status", "is_delete", "outlier");
//
//        // 2. 添加条件过滤
//        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
//        if (startTime != null) {
//            boolQuery.must(QueryBuilders.rangeQuery("end_time").gte(startTime).lte(endTime));
//        }
//        boolQuery.must(QueryBuilders.termsQuery("status", Arrays.asList(NOT_CLEANED, IS_WHITE, IS_BLACK).toArray()))
//                .must(QueryBuilders.termsQuery("param_id", newparamIdSet.toArray()))
//                .must(QueryBuilders.termsQuery("model_id", newmodelIdSet.toArray()))
//                .must(QueryBuilders.termQuery("is_delete", NOT_DELETED))
//                .must(QueryBuilders.termQuery("outlier", ABNORMOL));
//
//        queryBuilder.withQuery(boolQuery);
//
//        // 3. 添加分组和获取最新记录
//        String aggregationName = "group_by_param_model";
//        TermsAggregationBuilder paramAggregation = AggregationBuilders.terms(aggregationName).field("param_id");
//        TermsAggregationBuilder modelAggregation = AggregationBuilders.terms("group_by_model").field("model_id")
//                .subAggregation(AggregationBuilders.topHits("latest_record")
//                        .sort(SortBuilders.fieldSort("end_time").order(SortOrder.DESC))
//                        .size(1)); // 获取每组的最新记录
//        paramAggregation.subAggregation(modelAggregation);
//        queryBuilder.addAggregation(paramAggregation);
//
//        List<TbLParamMalfunctionRecordDO> resultList = new ArrayList<>();
//        Map<String, Integer> countMap = new HashMap<>();
//        // 4. 执行查询
//        Query searchQuery = queryBuilder.build();
//        SearchHits<TbLParamMalfunctionRecordDO> searchHits = elasticsearchRestTemplate.search(searchQuery, TbLParamMalfunctionRecordDO.class);
//        Aggregations aggregations = (Aggregations) searchHits.getAggregations().aggregations();
//        ParsedLongTerms groupByParamModelParsedLongTerms = (ParsedLongTerms) aggregations.getAsMap().get("group_by_param_model");
//        groupByParamModelParsedLongTerms.getBuckets().forEach(bucket -> {
//            ParsedLongTerms groupedByModelParsedLongTerms = (ParsedLongTerms) bucket.getAggregations().getAsMap().get("group_by_model");
//            groupedByModelParsedLongTerms.getBuckets().forEach(modelbucket -> {
//                ParsedTopHits latestRecord = (ParsedTopHits) modelbucket.getAggregations().getAsMap().get("latest_record");
//                long docCount = modelbucket.getDocCount();
//                countMap.put(bucket.getKeyAsString() + "_" + modelbucket.getKeyAsString(), (int) docCount);
//                for (SearchHit hit : latestRecord.getHits().getHits()) {
//                    TbLParamMalfunctionRecordDO record = JSON.parseObject(hit.getSourceAsString(), TbLParamMalfunctionRecordDO.class); // 反序列化为DO对象
//                    resultList.add(record);
//                }
//            });
//        });
//        // 6. 根据 endTime 排序
//        resultList.sort((o1, o2) -> o2.getEndTime().compareTo(o1.getEndTime()));
//
//        // 7. 分页
//        int fromIndex = (pageNum - 1) * pageSize;
//        int toIndex = Math.min(fromIndex + pageSize, resultList.size());
//        if (fromIndex >= resultList.size()) {
//            return new ArrayList<>(); // 如果起始索引超出范围，返回空列表
//        }
//        resultList.subList(fromIndex, toIndex).forEach(
//                record -> {
//                    if (countMap.containsKey(record.getParamId() + "_" + record.getModelId())) {
//                        System.out.println(record.getId() + ":" + countMap.get(record.getParamId() + "_" + record.getModelId()));
//                    }
//                }
//        );
//        return resultList.subList(fromIndex, toIndex);
//    }
//
//    public void deleteById(int id) {
//        tbLParamMalfunctionRecordRepository.deleteById(id);
//    }
//}
